/**-----------------------------------海量点 -------------------------------*/
/**-------------海量点ui加载 ---------------------*/
AMapUI.loadUI(['misc/PointSimplifier'], function(PointSimplifier) {

    if (!PointSimplifier.supportCanvas) {
        alert('当前环境不支持 Canvas！');
        return;
    }

    //启动页面
    initPage(PointSimplifier);
});
/**-------------组件创建与配置 --------------------*/
function initPage(PointSimplifier) {
    //创建组件实例
    var pointSimplifierIns = new PointSimplifier({
        map: map, //关联的map
        autoSetFitView:false,
        compareDataItem: function(a, b, aIndex, bIndex) {
            //数据源中靠后的元素优先，index大的排到前面去
            return aIndex > bIndex ? -1 : 1;
        },
        getPosition: function(dataItem) {
            //返回数据项的经纬度，AMap.LngLat实例或者经纬度数组
            return dataItem.position;
        },
        getHoverTitle: function(dataItem, idx) {
            if(dataItem.type=='mobile'){
                var info = "</br><font color='#FFFFFF'>电话："+dataItem.mobile+"</font>"
            }else{
                var info = "</br><font color='#FFFFFF'>种类："+dataItem.category+"</font>"
            }
            infoWindow.setContent(updateInfoWindow(dataItem.name,info));
            infoWindow.open(map, dataItem.position);
        },
        renderConstructor: PointSimplifier.Render.Canvas.GroupStyleRender,

        renderOptions: {
            getGroupId:function(item, idx){
                return item.type;
            },
            groupStyleOptions:{
                "mobile":{
                    //点的样式
                    pointStyle: {
                        content:PointSimplifier.Render.Canvas.getImageContent( '/image/4.png',   

                        function onload() {
        
                            //图片加载成功，重新绘制一次
        
                            pointSimplifierIns.renderLater();
        
                        },
        
                        function onerror(e) {
        
                            alert('图片加载失败！');
        
                        }),
                        width:35,
                        height:35
                    },
                },
                "broadcast":{
                    //点的样式
                    pointStyle: {
                        content:PointSimplifier.Render.Canvas.getImageContent( '/image/5.png',   

                        function onload() {
        
                            //图片加载成功，重新绘制一次
        
                            pointSimplifierIns.renderLater();
        
                        },
        
                        function onerror(e) {
        
                            alert('图片加载失败！');
        
                        }),
                        width:20,
                        height:20
                    },

                }
            },
        }
    });

    // axios获取点并标注
    setInterval(markit,5000);
    function markit(){
        getPoint();
        getPoint_broad();
        setData_(pointSimplifierIns,data1,data2);
    }
    getPoint(pointSimplifierIns);
    // //监听事件
    pointSimplifierIns.on('pointClick', function(e, record) {
        map.setZoom(16);
        var position = record.data.position;
        map.setCenter(position);
    });
    // 鼠标离开
    pointSimplifierIns.on('pointMouseout',function(e,record){
        closeInfoWindow();
    });
}
/**-------------生成随机点 ------------------------*/
//仅作示意
function createPoints(center, num) {
    var data = [];
    for (var i = 0, len = num; i < len; i++) {
        data.push({
            position: [
                center.getLng() + (Math.random() > 0.5 ? 1 : -1) * Math.random(),
                center.getLat() + (Math.random() > 0.5 ? 1 : -1) * Math.random()
            ]
        });
    }
    return data;
}
var data1;
var data2;
/**-------------axios 获取点----------------------------*/
/**检测人员 */
function getPoint(){
    axios
    .get('/d/isworking')
    .then(function(response){
        var position_list_o = response.data.working_list;
        data1 = render_data(position_list_o);
    })
    .catch(function(error){
        console.log(error)
        return null;
    });
}
/**黑广播 */
function getPoint_broad(){
    axios
    .get('/d/broadcast')
    .then(function(response){
        var broadcast = response.data.brocastlist;
        data2 = make_data(broadcast);
    })
    .catch(function(error){
        console.log(error)
        return null;
    })
}
/**------处理数据 ------*/
/**检测人员 */
function render_data(position_list_o){
    var data = []
    var p_list;
    var mobile;
    var name;
    var p_;

    for(var item in position_list_o){
        mobile = item;
        p_ = position_list_o[item];
        p_list = p_["location"]; 
        name = p_["name"];
        render_tool(data,p_list,mobile,name);
    }
    return data;
}
/**黑广播 */
function make_data(bro){
    var data=[]
    var d_;
    var name;
    var channel;
    var category;
    var polislist
    for(var i=0;i<bro.length;i++){
        d_ = bro[i];
        name = d_.name;
        // alert(name);
        channel = d_.channel;
        category = d_.category;
        polislist = d_.location;
        make_tool(data,name,channel,category,polislist)
    }
    return data;
}
/**-----绘制点用工具 --*/
/**检测人员 */
function render_tool(data,p_list,mobile,name){
    var posi = String(p_list[0]);
    var lnglat = posi.split(",");
    var lng = lnglat[0];
    var lat = lnglat[1];
    data.push({
        position:[
            lng,lat
        ],
        name:name,
        mobile:mobile,
        type:'mobile'
    });
}
/**黑广播 */
function make_tool(data,name,channel,category,polislist){
   var posi;
   var lng;
   var lat;
    for (var i=0;i<polislist.length;i++){
        posi = polislist[i];
        // alert(posi);
        var lnglat2 = posi.split(',');
        lng = lnglat2[0];
        // alert('lng: '+lng);
        lat = lnglat2[1];
        // alert('lat: '+lat);
        data.push({
            position:[
                lng,lat
            ],
            name:name,
            channel:channel,
            category:category,
            type:'broadcast'
        });
    }
}
/**----设置数据源 --*/
function setData_(pointSimplifierIns,data1,data2){
    var data = data1.concat(data2);
    pointSimplifierIns.setData(data);
    // 给移动端设置简单标注
    for(var i=0;i<data1.length;i++){
        var d = data1[i]
        var string = d.position; 
        var name = d.name;
        var lng = string[0];
        var lat = string[1];
        var ln =new AMap.LngLat(lng,lat,true);
        simplemarker(ln,name);
    }
    // 清空简单标注
    var over_lays = map.getAllOverlays('marker');
    clearSimplemarker(over_lays);
}
/**-----------------------------------信息窗口 ------------------------------*/
/**-------------信息窗口内容 -----------------------*/
//实例化信息窗体
var title = '监测人员';
var content = [];
content.push("<font color='#FFFFFF'>姓名：监测人员１</font>");
content.push("<font color='#FFFFFF'>电话：64733333</font>");
/**-------------实例化组件 -------------------------*/
var infoWindow = new AMap.InfoWindow({
    isCustom: true,  //使用自定义窗体
    content: createInfoWindow(title, content.join("<br/>")),
    offset: new AMap.Pixel(16, -45)
});

/** 构建自定义信息窗体*/
function createInfoWindow(title, content) {
    var info = document.createElement("div");
    info.className = "custom-info input-card content-window-card";

    //可以通过下面的方式修改自定义窗体的宽高
    //info.style.width = "400px";
    // 定义顶部标题
    var top = document.createElement("div");
    var titleD = document.createElement("div");
    var closeX = document.createElement("img");
    top.className = "info-top";
    titleD.innerHTML = title;
    closeX.src = "https://webapi.amap.com/images/close2.gif";
    closeX.onclick = closeInfoWindow;

    top.appendChild(titleD);
    top.appendChild(closeX);
    info.appendChild(top);

    // 定义中部内容
    var middle = document.createElement("div");
    middle.className = "info-middle";
    middle.style.backgroundColor = 'rgb(0,0,0,0.5)';
    middle.innerHTML = content;
    info.appendChild(middle);

    // 定义底部内容
    var bottom = document.createElement("div");
    bottom.className = "info-bottom";
    bottom.style.position = 'relative';
    bottom.style.top = '0px';
    bottom.style.margin = '0 auto';
    var sharp = document.createElement("img");
    sharp.src = "https://webapi.amap.com/images/sharp.png";
    bottom.appendChild(sharp);
    info.appendChild(bottom);
    return info;
}
/**动态更新信息窗体 */
function updateInfoWindow(name,phonenum){
    // var title = '监测人员';
    var content_ = [];
    content_.push("<font color='#FFFFFF'>姓名："+name+"</font>");
    content_.push(phonenum);
    var info = createInfoWindow(title,content_);
    return info; 
}
//关闭信息窗体
function closeInfoWindow() {
    map.clearInfoWindow();
}
/**------------------------------------简单标注 ------------------------------*/
function simplemarker(lnglat,string){
    // var mar;
    AMapUI.loadUI(['overlay/SimpleMarker'], function(SimpleMarker) {

         new SimpleMarker({
            // iconLabel: {
            //     innerHTML: '<i>B</i>', //设置文字内容
            //     style: {
            //         color: '#fff' //设置文字颜色
            //     }
            // },
            iconStyle: {
                style:{
                    width:'1px',
                    height:'1px'
                }
            },

            map: map,
            position: lnglat,

            label: {
                // content: iconStyles,
                content:string,
                offset: new AMap.Pixel(27, 25)
            }
        });

    });
    // return mar;
}
/**清楚简单标注 */
function clearSimplemarker(ob_list){
    if(ob_list.length>0){
        for(var i=0;i<ob_list.length;i++){
            map.remove(ob_list[i]);
        }
    }
}